<?php

namespace addons\shopro\job;

use addons\shopro\library\notify\channel\Database;
use addons\shopro\library\traits\ActivityCache;
use addons\shopro\library\traits\Groupon;
use addons\shopro\model\Activity;
use addons\shopro\model\ActivityGroupon;
use think\Db;
use think\queue\Job;


/**
 * 订单自动操作
 */
class ActivityGrouponAutoOper extends BaseJob
{
    use ActivityCache, Groupon;

    /**
     * 拼团判断，将团结束, 
     */
    public function expire(Job $job, $data){
        try {
            $activity = $data['activity'];
            $activity_groupon_id = $data['activity_groupon_id'];
            $activityGroupon = ActivityGroupon::where('id', $activity_groupon_id)->find();

            // 活动正在进行中， 走这里的说明人数 都没满
            if ($activityGroupon && $activityGroupon['status'] == 'ing') {
                if (!empty($activity)){
                    \think\Db::transaction(function () use ($activity, $activityGroupon) {
                        $rules = $activity['rules'];
                        // 是否虚拟成团
                        $is_fictitious = $rules['is_fictitious'] ?? 0;
                        // 最大虚拟人数 ,不填或者 "" 不限制人数，都允许虚拟成团， 0相当于不允许虚拟成团
                        $fictitious_num = (!isset($rules['fictitious_num']) || $rules['fictitious_num'] == '') ? 'no-limit' : $rules['fictitious_num'];

                        //开始-2022-1-27 Ripple 拼团有不限人数的
                        if ($activityGroupon['current_num'] <= 0){//当前拼团人数为0 直接解散
                            $this->invalidRefundGroupon($activityGroupon);
                        }else{
                            if ($activityGroupon['num'] > 0){//有成团人数
                                //获取真实参团人数
                                $true_people = Db::name('shopro_activity_groupon_log')
                                    ->where([
                                        'groupon_id'=>$activityGroupon['id'],
                                        'is_fictitious'=>0,
                                        'order_id'=>['gt',0]
                                    ])
                                    ->count();
                                if ($true_people > 0){
                                    // 拼团剩余人数
                                    $surplus_num = $activityGroupon['num'] - $activityGroupon['current_num'];
                                    //允许虚拟团员
                                    if ($is_fictitious){
                                        //不限制虚拟人数 或 最高虚拟人数>=剩余人数
                                        if ($fictitious_num == 'no-limit' || ($fictitious_num >= $surplus_num)) {
                                            //如果团长可以不参加拼团 且 拼团剩余人数=成团人数 即没人参团需要解散拼团
                                            if (($rules['not_participate']) && ($surplus_num == $activityGroupon['num'])){
                                                // 解散退款
                                                $this->invalidRefundGroupon($activityGroupon);
                                            }else{
                                                // 虚拟成团，如果虚拟用户不够，则自动解散
                                                $this->finishFictitiousGroupon($activityGroupon);
                                            }
                                        } else {
                                            // 解散退款
                                            $this->invalidRefundGroupon($activityGroupon);
                                        }
                                    }else{//不允许
                                        if ($surplus_num <= 0){//成团
                                            $this->finishFictitiousGroupon($activityGroupon);
                                        }else{//解散
                                            $this->invalidRefundGroupon($activityGroupon);
                                        }

                                    }
                                }else{
                                    // 解散退款
                                    $this->invalidRefundGroupon($activityGroupon);
                                }

                            }else{//不限人数

                                //如果团长可以不参加拼团 且 团人数仅为1人 即只有团长参与则解散
                                if (($rules['not_participate']) && ($activityGroupon['current_num'] == 1)){
                                    // 解散退款
                                    $this->invalidRefundGroupon($activityGroupon);
                                }else{
                                    //获取真实参团人数
                                    $true_people = Db::name('shopro_activity_groupon_log')
                                        ->where([
                                            'groupon_id'=>$activityGroupon['id'],
                                            'is_fictitious'=>0,
                                            'order_id'=>['gt',0]
                                        ])
                                        ->count();
                                    if ($true_people > 0){//有真实人参加
                                        //获取已经添加的虚拟人id
                                        $false_user_ids = Db::name('shopro_activity_groupon_log')
                                            ->where([
                                                'groupon_id'=>$activityGroupon['id'],
                                                'is_fictitious'=>1,
                                            ])->column('user_id');
                                        //获取其它虚拟人数，排除已经添加的虚拟人数
                                        if (!empty($false_user_ids)){
                                            $add_false_user = Db::name('shopro_user_fake')->where([
                                                'id' => ['not in',$false_user_ids]
                                            ])->orderRaw('rand()')->limit($true_people)->select();
                                        }else{
                                            $add_false_user = Db::name('shopro_user_fake')
                                                ->orderRaw('rand()')->limit($true_people)->select();
                                        }
                                        //有足够的虚拟人员
                                        if (count($add_false_user) == $true_people){//将团当前人数+真实参团人数 更新为成团人数
                                            //更新成团人数
                                            Db::name('shopro_activity_groupon')->where(['id'=>$activityGroupon['id']])->update(['num'=>($activityGroupon['current_num'] + $true_people)]);
                                            $activityGroupon = ActivityGroupon::where('id', $activityGroupon['id'])->find();

                                            // 虚拟成团，如果虚拟用户不够，则自动解散
                                            $this->finishFictitiousGroupon($activityGroupon,$true_people,$add_false_user);
                                        }else{//将团当前人数 更新为成团人数
                                            //更新成团人数
                                            Db::name('shopro_activity_groupon')->where(['id'=>$activityGroupon['id']])->update(['num'=>$activityGroupon['current_num']]);
                                            $activityGroupon = ActivityGroupon::where('id', $activityGroupon['id'])->find();

                                            // 虚拟成团，如果虚拟用户不够，则自动解散
                                            $this->finishFictitiousGroupon($activityGroupon);
                                        }
                                    }else{//无真实人参加
                                        // 解散退款
                                        $this->invalidRefundGroupon($activityGroupon);
                                    }

                                }
                            }
                        }
                        //结束-2022-1-27 Ripple 拼团有不限人数的

                        //老代码
                        /*// 拼团剩余人数
                        $surplus_num = $activityGroupon['num'] - $activityGroupon['current_num'];
                        if ($is_fictitious && ($fictitious_num == 'no-limit' || $fictitious_num >= $surplus_num)) {
                            // 虚拟成团，如果虚拟用户不够，则自动解散
                            $this->finishFictitiousGroupon($activityGroupon);
                        } else {
                            // 解散退款
                            $this->invalidRefundGroupon($activityGroupon);
                        }*/

                    });
                }else{//新拼团
                    \think\Db::transaction(function () use ($activityGroupon) {

                        // 是否虚拟成团
                        $is_fictitious = $activityGroupon['is_fictitious'] ?? 0;
                        if (!$is_fictitious){//不允许虚拟拼团
                            if ($activityGroupon['current_num'] >= $activityGroupon['min_num']){//人数达到最低值 更新拼团成团人数为最低值
                                Db::name('shopro_activity_groupon')->where(['id'=>$activityGroupon['id']])->update(['num'=>$activityGroupon['current_num']]);
                                $activityGroupon = ActivityGroupon::where('id', $activityGroupon['id'])->find();
                                // 虚拟成团，如果虚拟用户不够，则自动解散
                                $this->finishFictitiousGroupon($activityGroupon);
                            }else{//人数未达到最低值 直接解散
                                // 解散退款
                                $this->invalidRefundGroupon($activityGroupon);
                            }
                        }else{//允许
                            if ($activityGroupon['current_num'] >= $activityGroupon['min_num']){//人数达到最低值 更新拼团成团人数为最低值
                                Db::name('shopro_activity_groupon')->where(['id'=>$activityGroupon['id']])->update(['num'=>$activityGroupon['current_num']]);
                                $activityGroupon = ActivityGroupon::where('id', $activityGroupon['id'])->find();
                            }

                            // 最大虚拟人数 ,不填或者 "" 不限制人数，都允许虚拟成团， 0相当于不允许虚拟成团
                            $fictitious_num = (!isset($activityGroupon['fictitious_num']) || empty($activityGroupon['fictitious_num'])) ? 'no-limit' : $activityGroupon['fictitious_num'];

                            $surplus_num = $activityGroupon['num'] - $activityGroupon['current_num'];
                            if ($is_fictitious && ($fictitious_num == 'no-limit' || $fictitious_num >= $surplus_num)) {
                                // 虚拟成团，如果虚拟用户不够，则自动解散
                                $this->finishFictitiousGroupon($activityGroupon);
                            } else {
                                // 解散退款
                                $this->invalidRefundGroupon($activityGroupon);
                            }

                        }

                        $this->delNewGroupon($activityGroupon['id']);

                    });
                }

            }else{
                if ($activityGroupon && empty($activity)){//新拼团
                    $this->delNewGroupon($activityGroupon['id']);
                }
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-expire' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }
    
}